package org.jeecg.modules.cas.util;

import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Component
public class HttpUtil {

    private static final RestTemplate restTemplate = new RestTemplate();

    /**
     * 发送 GET 请求
     *
     * @param url 请求的URL
     * @return 响应的 JSON 数据
     */
    public static String doGet(String url) {
        try {
            // 发送 GET 请求
            ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
            if (response.getStatusCode() == HttpStatus.OK) {
                return response.getBody();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 发送 POST 请求
     *
     * @param url     请求的URL
     * @param params  请求参数
     * @param headers 请求头（可选）
     * @return 响应的 JSON 数据
     */
    public static String doPost(String url, Map<String, Object> params, Map<String, String> headers) {
        try {
            // 设置请求头
            HttpHeaders httpHeaders = new HttpHeaders();
            if (headers != null) {
                headers.forEach(httpHeaders::add);
            }
            httpHeaders.setContentType(MediaType.APPLICATION_JSON);

            // 构建请求体
            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(params, httpHeaders);

            // 发送 POST 请求
            ResponseEntity<String> response = restTemplate.postForEntity(url, requestEntity, String.class);
            if (response.getStatusCode() == HttpStatus.OK) {
                return response.getBody();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}